package com.ezcolour.ticket.admin.controller;

import com.ezcolour.ticket.base.BaseController;
import com.ezcolour.ticket.base.BaseException;
import com.ezcolour.ticket.common.annotion.BussinessLog;
import com.ezcolour.ticket.common.annotion.Permission;
import com.ezcolour.ticket.common.shiro.Const;
import com.ezcolour.ticket.common.shiro.ShiroKit;
import com.ezcolour.ticket.model.Role;
import com.ezcolour.ticket.model.User;
import com.ezcolour.ticket.service.RoleService;
import com.ezcolour.ticket.service.UserService;
import com.ezcolour.ticket.support.BizExceptionEnum;
import com.ezcolour.ticket.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    /**
     * 跳转到角色管理页面
     */
    @RequestMapping(value = "/roles", method = RequestMethod.GET)
    @Permission(Const.ADMIN_NAME)
    public String role(Model model) {
        model.addAttribute("roleList", roleService.findAll());
        return  "/admin/role";
        
    }

    /**
     * 跳转到角色修改添加页面
     */
    @RequestMapping(value = "/role", method = RequestMethod.GET)
    @Permission(Const.ADMIN_NAME)
    public String roleView(Model model) {
        model.addAttribute("roleList", roleService.findAll());
        return  "/admin/roleInfo";
    }

    /**
     * 角色新增
     */
    @RequestMapping(value = "/role", method = RequestMethod.POST)
    @BussinessLog(value = "添加角色", key = "name")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseEntity<?> add(@Valid Role role, BindingResult result) {
        if (result.hasErrors()) {
            throw new BaseException(BizExceptionEnum.REQUEST_NULL);
        }
        Long count = roleService.count();
        role.setNum( ++count );
        if(role.getPid() == null || role.getPid().equals(0)){
            role.setPid(0L);
        }
        roleService.save(role);
        return ResponseEntity.ok("success");
    }
}
